<template>
  <div id="index">
    <el-row>
      <el-col>
        <div id="main">
          <h1 class="title">个人网上银行</h1>
          <el-form ref="loginForm" :rules="rules" :model="loginForm" class="form">
            <el-form-item label="卡号" label-width="60px" prop="cardno">
              <el-input v-model="loginForm.cardno"></el-input>
            </el-form-item>
            <el-form-item label="密码" label-width="60px" prop="password">
              <el-input v-model="loginForm.password" show-password></el-input>
            </el-form-item>
            <el-form-item class="button">
              <el-button type="primary" @click="onSubmit('loginForm')">登录网上银行</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {post} from "../common/request";
import jwt_decode from "jwt-decode";

export default {
  name: "Login",
  data() {
    return {
      loginForm: {
        cardno: 1111111111111111,
        password: 123456
      },
      rules: {
        cardno: [
          {required: true, message: '请输入卡号', trigger: 'blur'},
          {
            pattern: /^\d{16}$/,
            message: "请正确填写16位卡号",
            trigger: "blur"
          }
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {
            pattern: /^\d{6}$/,
            message: "请正确填写6位登录密码",
            trigger: "blur"
          }
        ]
      }
    }
  },
  methods: {
    onSubmit(loginForm) {
      this.$refs[loginForm].validate((valid) => {
        if (valid) {
          post("/account/doLogin", this.loginForm).then(x => {
            if (x.code === 1) {
              let token = jwt_decode(x.data);
              let UserInfo = token.user;

              //保存数据到 Vuex
              this.$store.dispatch('asyncUpdateUser', UserInfo);
              this.$store.dispatch('asyncUpdateToken', x.data);
              //保存到浏览器本地空间
              sessionStorage.setItem('state', JSON.stringify(this.$store.state));

              this.$message.success(x.msg);
              this.$router.push("/Home");
            } else {
              this.$message.error(x.msg);
            }
          });
        } else {
          this.$message.error("登录失败，请重新登录")
          return false;
        }
      });

    }
  }
}
</script>

<style scoped>
#index {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

#main {
  background-color: rgba(144, 238, 144, 0.4);
  border-radius: 10px;

  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.title {
  margin-top: 30px;
}

.form {
  padding: 40px 80px 40px 80px;
}

.button {
  text-align: center;
}
</style>
